#include "rov_config.h"
#include "heartbeat_thread.h"

MYHeartbeatThread::MYHeartbeatThread(CONFIG* config)
{
    send_config = config;
}

void MYHeartbeatThread::run()
{
    long long last_timestamp, timestamp;
    auto now = std::chrono::system_clock::now();
    auto duration = now.time_since_epoch();
    last_timestamp = std::chrono::duration_cast<std::chrono::microseconds>(duration).count();

    std::vector<uint8_t> buffer;
    udp::RecvInfo info;

    udp::UDPReceiver udp_receiver;
    udp_receiver.set_listen_port(7777);
    udp::UDPSender udp_sender;
    udp_sender.set_target_port(8888);

    if (!udp_receiver.init())
    {
        emit update_heartbeat_log("UDP网络组件启动失败！");
    }
    else
    {
        emit update_heartbeat_log("UDP网络组件启动成功！");
        emit update_heartbeat_log("正在连接机器人......");
        qDebug() << "yes";
    }

    CONFIG* recv_config;
    int heartbeat_state = 1;
    while (true)
    {
        now = std::chrono::system_clock::now();
        duration = now.time_since_epoch();
        timestamp = std::chrono::duration_cast<std::chrono::microseconds>(duration).count();
        buffer = udp_receiver.recv(info);
        if (info.flag == FLAG_SUCCESS)
        {
            if (timestamp - last_timestamp >= 4 * 1000 * 1000)
            {
              heartbeat_state = 1;
              emit update_heartbeat_log("已恢复连接");
            }
            qDebug() << "success";
            //emit update_heartbeat_log("recv success");
            //emit update_heartbeat_log(QString("接收到来自")  );
            last_timestamp = std::chrono::duration_cast<std::chrono::microseconds>(duration).count();
        }
        else if ( (heartbeat_state == 1) && (timestamp - last_timestamp >= 4 * 1000 * 1000) )
        {
            heartbeat_state = 0;
            emit update_heartbeat_log("十秒内已无连接");
        }
        emit update_heartstate(heartbeat_state);
    }
}
